package com.yunsoft.controller;

import java.util.HashMap;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.yunsoft.Constants;
import com.yunsoft.pojo.User;
import com.yunsoft.pojo.WeiXinObject;
import com.yunsoft.service.UserService;
import com.yunsoft.service.impl.UserServiceImpl;
import com.yunsoft.util.HttpRequestUtil;
import com.yunsoft.util.StringFunction;
@Controller
public class UserController extends BasicController {
	
	@Autowired
	UserService userServiceImpl;
	
	@RequestMapping(value ="/wexinLogin",method=RequestMethod.POST)
	@ResponseBody
	public HashMap<String, Object> weixinLogin(
			@RequestParam(value = "code", required = true) String code,
			@RequestParam(value = "sex", required = true) int sex,
			@RequestParam(value = "country", required = true) String country,
			@RequestParam(value = "province", required = true) String province,
			@RequestParam(value = "city", required = true) String city,
			@RequestParam(value = "nickName", required = true) String nickName,
			@RequestParam(value = "avatarUrl", required = true) String avatarUrl,
			@RequestParam(value = "sourceType", required = false) String sourceType
	){
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		String param ="appid="+Constants.wexinAppId+"&secret="+Constants.wexinSecret+"&js_code="+code+"&grant_type=authorization_code";
		String json;
		try {
			json = HttpRequestUtil.sendGet(url, param);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return returnErrorMessage(e.getMessage(),null);
		}
		if (StringFunction.isNotNull(json)){
		WeiXinObject ob = (WeiXinObject) JSONObject.parseObject(json, WeiXinObject.class);
		System.out.println(ob.getOpenid()+"=="+ob.getSession_key());
		
		User user = userServiceImpl.insertWxLoginUser(new User.Builder().avatarUrl(avatarUrl).city(city).province(province).country(country).sex(sex).nickName(nickName).sessionKey(ob.getSession_key()).openId(ob.getOpenid()).build());
		
		return returnSuccessData("", user);
		}
		return returnNoData("", null);
	}

}
